#include <stdio.h>
#include "helpers.h"
#include "genlib.h"
#include <direct.h>
#include <stddef.h>
#include <stdio.h>
#include <sys/types.h>
#include "dirent.h"
#include <strlib.h>
#include <simpio.h>

void printGraph(int **graph, int graphSize){
	int i,j;
	for(j = 0; j < graphSize; j++){
		for(i = 0; i < graphSize; i++){
			printf("%4d", graph[i][j]);
		}
		printf("\n");
	}
}
void countEdges(int **graph, int graphSize){
	int i, j, edges = 0;
	for(j = 0; j < graphSize; j++){
		for(i = 0; i < graphSize; i++){
			if(graph[i][j] != 0 && graph[i][j] != 999){
				edges++;
			}
		}
	}
}
int **readGraph(int *graphSize){
	int k, i, j, choice, **graph;
	string filename;
	FILE *infile;

	filename = getFilename();

	infile = fopen(filename, "r");
	fscanf(infile, "%d\n", graphSize);

	graph = newMatrix(*graphSize);

	for(j = 0; j < *graphSize; j++){
		for(i = 0; i < *graphSize; i++){
			fscanf(infile, "%4d", &graph[i][j]);
		}
		fscanf(infile, "\n");
	}
	return graph;
}

int **newMatrix(int size){
	int i, **newMatrix = NewArray(size, int *);

	for(i = 0; i < size; i++){
		newMatrix[i] = NewArray(size, int);
	}
	return newMatrix;
}

string getFilename(void){
	DIR *dp;
	struct dirent *ep;
	string filer[100],tempstring,stringend;
	int i=0,filesnumber=0;

	dp = opendir ("./");
	if (dp != NULL)
	{
		while (ep = readdir (dp)){
			tempstring=ep->d_name;
			stringend=SubString(tempstring,StringLength(tempstring)-4,StringLength(tempstring));
			if(StringEqual(stringend,".txt")) {
				filer[filesnumber]=CopyString(tempstring);
				filesnumber++;
			}
			i++;
		}
		(void) closedir (dp);
	}
	else
		perror ("Couldn't open the directory");
	
	printf("Available .txt files\n\n");
	for(i=0;i<filesnumber;i++){
		printf("%d\t%s\n", i+1,filer[i]);
	}

	printf("\n0\tTo enter filename\n");
	
	printf("\nChoose file to load:\n");
	i=GetInteger();
	if(i==0) return(GetLine());
	i--;

	return(filer[i]);
}